package com.cykj.pos.util;

import com.jeesuite.common.json.JsonUtils;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: 魏建波
 * Date: 2021/5/27
 * Time: 14:32
 * Description:
 */
public class HttpUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class);

    private static OkHttpClient client = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS).build();

    public static String httpGet(String url) {
        try {
            Request request = new Request.Builder().url(url).build();
            Response response = client.newCall(request).execute();
            try {
                if(response.isSuccessful()){
                    return response.body().string();
                }
            } finally {
                response.close();
            }
            throw new AygBaseBizException(1001, response.message());
        } catch (Exception e) {
            LOGGER.error("httpGet error，url:"+url, e);
            throw new AygBaseBizException(400, "请求第三方错误");
        }
    }

    public static  String httpPost(String url, Map<String, Object> params) {
        try {
            FormBody.Builder builder = new FormBody.Builder();
            for (String key : params.keySet()) {
                builder.add(key, params.get(key).toString());
            }

            RequestBody body = builder.build();
            Request request = new Request.Builder().url(url).post(body).build();
            Response response = client.newCall(request).execute();

            try {
                if(response.isSuccessful()){
                    return response.body().string();
                }
            } finally {
                response.close();
            }
            throw new AygBaseBizException(1001, response.message());
        } catch (Exception e) {
            LOGGER.error("httpGet error", e);
            throw new AygBaseBizException(400, "请求第三方错误");
        }
    }

    public static  String httpPostJson(String url,Object params) {
        try {
            RequestBody body = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                    , JsonUtils.toJson(params));
            Request request = new Request.Builder().url(url).post(body).build();
            Response response = client.newCall(request).execute();

            try {
                if(response.isSuccessful()){
                    return response.body().string();
                }
            } finally {
                response.close();
            }
            throw new AygBaseBizException(1001, response.message());
        } catch (Exception e) {
            // 回退
            LOGGER.error("httpGet error", e);
            throw new AygBaseBizException(400, "请求第三方错误");
        }
    }
}